package com.hjwoo.app.utils;

import android.content.Context;
import android.content.SharedPreferences.Editor;

import com.hjwoo.app.been.UserAccessTokenOBJ;

/**
 * 用于保存用户登录状态
 */
public class LoanAccessTokenIdKeeper
{
    private static final String PREFERENCES_NAME = "com_hjwoo_android";

    private static final String KEY_APPSESSIONID = "appSessionId";
//    private static final String KEY_ACCESS_TOKEN  = "access_token";
//    private static final String KEY_EXPIRES_IN    = "expires_in";

    /**
     * 保存 Token 对象到 SharedPreferences。
     *
     * @param context            应用程序上下文环境
     * @param userAccessTokenOBJ Token 对象
     */
    public static void writeAccessToken(Context context, UserAccessTokenOBJ userAccessTokenOBJ)
    {
        if (null == context || null == userAccessTokenOBJ)
        {
            return;
        }

        android.content.SharedPreferences pref   = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        Editor                            editor = pref.edit();
        editor.putString(KEY_APPSESSIONID, userAccessTokenOBJ.getAppSessionId());
//        editor.putString(KEY_ACCESS_TOKEN, userAccessTokenOBJ.getToken());
//        editor.putLong(KEY_EXPIRES_IN, userAccessTokenOBJ.getExpiresTime());
        editor.commit();
    }

    /**
     * 从 SharedPreferences 读取 Token 信息。
     *
     * @param context 应用程序上下文环境
     * @return 返回 Token 对象
     */
    public static UserAccessTokenOBJ readAccessToken(Context context)
    {
        if (null == context)
        {
            return null;
        }

        UserAccessTokenOBJ userAccessTokenOBJ = new UserAccessTokenOBJ();
        android.content.SharedPreferences pref               = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        userAccessTokenOBJ.setAppSessionId(pref.getString(KEY_APPSESSIONID, ""));
//        userAccessTokenOBJ.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
//        userAccessTokenOBJ.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));
        return userAccessTokenOBJ;
    }

    /**
     * 清空 SharedPreferences 中 Token信息。
     *
     * @param context 应用程序上下文环境
     */
    public static void clear(Context context)
    {
        if (null == context)
        {
            return;
        }

        android.content.SharedPreferences pref   = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        Editor                            editor = pref.edit();
        editor.clear();
        editor.commit();
    }
}
